angular使用websocket 实现数据定时刷新(ng2-stomp)

STOMP通过WebSocket为angular2服务可与:angular4和ionic3兼容

1.下载插件

分别执行以下指令

npm install stompjs --save
npm install sockjs-client --save
npm install ng2-stomp-service --save

2.添加stompjs和sockjs-client模块声明

在 - > typings.d.ts中添加

declare module 'stompjs';
declare module 'sockjs-client';

3.配置 angular-cli.json

使用angular-cli 创建的项目,那么在 - > angular-cli.json中添加以下代码,目的引入js(如果不是,我也不知道)

"../node_modules/sockjs-client/dist/sockjs.min.js",
"../node_modules/stompjs/lib/stomp.js"

4.配置 tsconfig.json

在compilerOptions的同级下添加

"include": [
"src/**/*",
"node_modules/ng2-stomp-service/dist/stomp.service.ts"
]

5.在app.module.ts中声明stompService

{provide:'stompService',useClass:StompService}

6.使用(以上准备好后开始使用吧)

SleepmonitorComponent.ts

import {Component, Inject, OnDestroy, OnInit} from '@angular/core';
import {StompService} from 'ng2-stomp-service';
import {Subscription} from 'rxjs/Subscription';
import {environment} from '../../../environments/environment';

@Component({
selector: 'app-sleepmonitor',
templateUrl: './sleepmonitor.component.html',
styleUrls: ['./sleepmonitor.component.css']
})
export class SleepmonitorComponent implements OnInit, OnDestroy {
subscription: Subscription = null;
userId = '';
constructor(@Inject('stompService') private stomp: StompService) { // 注入stompService
stomp.configure({ // 配置要连接的服务器地址
host: "http:127.0.0.1:8080/ws" + '/test',// 监听的地址
queue: {'init': false}
});
}


ngOnDestroy(): void { // 组建销毁
this.disconnect(); // 组建销毁时断开连接
}

ngOnInit() { // 组建初始化
this.connect(); // 监听过程
}
connect(): void {
this.stomp.startConnect().then(() => {
this.stomp.done('init');
this.subscription = this.stomp.subscribe('/user/' + this.userId + '/message', // 服务器端返回的数据接收
(data) => {
console.log(data);
});
this.stomp.send('/app/test', {// 向服务器端发送请求数据
userId: this.userId,
isUse: 1
});
this.getCurrentData(); // 为了设置每隔两分钟向服务器请求数据
});
}

getCurrentData() {
setInterval(() => {
this.stomp.send('/app/tast', {
userId: this.userId,
isUse: 1
});
}, 120000);
}
disconnect(): void { // 关闭链接
this.stomp.send('/app/test', {
userId: this.userId,
isUse: 0
});
if (this.subscription != null) {
this.subscription.unsubscribe();
}
this.stomp.disconnect().then(() => {
});
}
}

7.后台代码

接收处理Action中

@RequestMapping(value = "/test", method = RequestMethod.POST)// 此行应该可以省略
@MessageMapping("/test")
public void test(@RequestBody UserDevice userDevice) {
try {
LOGGER.info("你的业务逻辑");
} catch (Exception e) {
LOGGER.error("websocket处理异常:【{}】", e.getMessage());
}
}

8.服务器端配置

SpringMVC配置类WebSocketConfig.class

package iguard.websocket.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;

@Configuration
@EnableWebSocketMessageBroker // 激活Websocket消息代理
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
// 代理目的地以/chat、/doctor为前缀,客户端订阅消息的前缀
config.enableSimpleBroker("/sleep", "/user");

// 应用程序以/app为前缀,客户端发送消息的前缀
config.setApplicationDestinationPrefixes("/app");
config.setUserDestinationPrefix("/user");
}

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
// 指向websocket连接的地址
registry.addEndpoint("/test").setAllowedOrigins("*").withSockJS();
}
}


-------------本文结束感谢您的阅读-------------
0%